package com.weihe.toolkit.poi;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class PoiExcelXLSXToolkit implements IPoiExcel{
	private FileInputStream fileInput;
	private XSSFWorkbook xwb;
	private XSSFSheet childSheet;

	@Override
	public Object getCellValue(int row, int column) {
		Object data = null;
		if(null != childSheet && row >= 0 && row < childSheet.getLastRowNum()){
			XSSFRow rowData = childSheet.getRow(row);
			if(null != rowData && column>=0 && column < rowData.getLastCellNum()){
				XSSFCell cell = rowData.getCell(column);
				if (null != cell) {
					switch (cell.getCellType()) {
					case XSSFCell.CELL_TYPE_NUMERIC: 
						data = cell.getNumericCellValue();
						break;
					case XSSFCell.CELL_TYPE_STRING: 
						data = cell.getStringCellValue();
						break;
					case XSSFCell.CELL_TYPE_BOOLEAN: // Boolean
						data = cell.getBooleanCellValue();
						break;
					case XSSFCell.CELL_TYPE_FORMULA: 
						data = cell.getCellFormula();
						break;
					case XSSFCell.CELL_TYPE_BLANK: 
						data = "";
						break;
					case XSSFCell.CELL_TYPE_ERROR: 
						break;
					default:
						System.out.print("unknown type!");
						break;
					}
				}
			}
		}
		return data;
	}

	@Override
	public String getCellStringValue(int row, int column) {
		String data = null;
		if(null != childSheet && row >= 0 && row < childSheet.getLastRowNum()){
			XSSFRow rowData = childSheet.getRow(row);
			if(null != rowData && column>=0 && column < rowData.getLastCellNum()){
				XSSFCell cell = rowData.getCell(column);
				if (null != cell) {
					data = cell.getStringCellValue();
				}
			}
		}
		return data;
	}

	@Override
	public void openExcel(String filePath) throws Exception {
		if(StringUtils.isNotBlank(filePath)){
			if(null == xwb){
				fileInput = new FileInputStream(filePath);
				xwb = new XSSFWorkbook(fileInput);
				this.childSheet = xwb.getSheetAt(0);
			}
		}else{
			throw new Exception("FilePath is null or blank");
		}
	}

	@Override
	public void openExcelSheet(int sheet) throws Exception {
		if(null != xwb){
			if(sheet >=0 && sheet < xwb.getNumberOfSheets()){
				childSheet = xwb.getSheetAt(sheet);
			}else{
				throw new Exception("Excel sheet error!");
			}
		}else{
			throw new Exception("Excel not exist!");
		}
	}

	@Override
	public void closeExcel() {
		if(null != fileInput){
			try {
				fileInput.close();
			} catch (IOException e) {
				fileInput = null;
			}
		}
	}

	

}
